"""
This file contains a socket server that serves up loopback sockets
currently used only in the SocketSelectable.
"""
from __future__ import absolute_import
import socket
import threading
from .singleton import SingletonMeta


class SocketServer(object):
    """
    This singleton class dispenses socket pairs of loopback sockets that it
    can use to talk to itself with.
    """
    __metaclass__ = SingletonMeta
    
    def __init__(self):
        # initialize the socket server
        socket_ = socket.socket()
        # bind to the first available port on the loopback interface
        address = '127.0.0.1'
        socket_.bind((address, 0))
        socket_.listen(1)
        socket_ .setblocking(0)
        self.address, self.port = socket_.getsockname()
        self.socket = socket_
        self.lock = threading.RLock()
        
    def get_socket_pair(self):
        """
        Get a pair of sockets that talk to each other over the loopback
        interface.
        """
        client_socket = socket.socket()
        # lock so that we don't queue up more than one connection
        with self.lock:
            client_socket.connect((self.address, self.port))
            # accept the queued connection
            server_socket, _address = self.socket.accept()
        return (client_socket, server_socket)